<!DOCTYPE HTML>
<html>
<head>
	<meta charset = "utf-8" />
	<meta name = "format-detection" content = "telephone = no" />
	<meta name = "msapplication-tap-highlight" content = "no" />
	<meta name = "viewport" content="initial-scale=1, minimum-scale=1" />

	<link rel = "stylesheet" href = "js/plugin/viewjs-1.6.3/view-1.6.3.min.css"/>

	<title>View.js</title>
</head>
<body>

	<script type = "text/javascript" src = "js/util.js"></script>
	<script type = "text/javascript" class = "viewjs">
	;(function(){
		var ajax = function(url, ops){
			ops = ops || {};

			var xhr = new XMLHttpRequest();
			xhr.open("GET", url);
			xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

			xhr.onreadystatechange = function(){
				if(this.readyState !== 4)
					return;

				ops.oncomplete && ops.oncomplete(this.responseText, this.status);

				if(this.status === 200){
					ops.onsuccess && ops.onsuccess.call(window, this.responseText);
				}else
					ops.onfailure && ops.onfailure.call(window, this.responseText, this.status);
			};
			xhr.send();
		};

		/**
		 * 设定参数默认值
		 */
		var setDftValue = function(ops, dftOps){
			ops = ops || {};
			dftOps = dftOps || {};

			/* 参数不存在时，从默认参数中读取并赋值 */
			for(var p in dftOps)
				if(!(p in ops))
					ops[p] = dftOps[p];

			return ops;
		};

		/**
		 * 应用代码
		 * @param {String} html 待应用的html
		 * @param {String} css 待应用的css
		 * @param {String} js 待应用的js
		 * @param {Object} [ctrl] 控制选项
		 * @param {Boolean} [ctrl.requireViewjsInitialized=true] 执行脚本时，是否要求View.js已经初始化
		 */
		window.apply = function(html, css, js, ctrl){
			ctrl = setDftValue(ctrl, {
				requireViewjsInitialized: true
			});

			if(null != html && (html = String(html).trim()) !== ""){
				var scriptObj = document.querySelector("script.viewjs");

				var tmpObj = document.createElement("div");
				tmpObj.innerHTML = html;
				var childNodes = tmpObj.childNodes;
				var arr = [];
				Array.prototype.forEach.call(childNodes, function(obj){
					arr.push(obj);
				});
				arr.forEach(function(obj){
					document.body.insertBefore(obj, scriptObj);
				});
			}

			if(null != css && (css = String(css).trim()) !== ""){
				var styleObj = document.createElement("style");
				styleObj.innerHTML = css;
				document.head.appendChild(styleObj);
			}

			ajax("js/plugin/viewjs-newest/view-newest.dev.min.js", {
				onsuccess: function(responseText){
					eval(responseText);

					if(ctrl.ifSpecifyViewjsInitializer){
						eval(js);
						return;
					}

					View.setInitializer(function(init){
						if(ctrl.requireViewjsInitialized){
							init();
							eval(js);
						}else{
							try{
								eval(js);
							}finally{
								init();
							}
						}
					}, "rightnow");
				}
			});
		};
	})();
	</script>
</body>
</html>